package com.jy.datapipeline.importserver.service.impl;

import com.jy.datapipeline.export.entity.DataSourceInfoModel;
import com.jy.datapipeline.export.service.DataSourceInfoService;
import com.jy.datapipeline.common.constants.ExpConstants;
import com.jy.datapipeline.common.constants.PrefixConstants;
import com.jy.datapipeline.common.exception.GlobalException;
import com.jy.datapipeline.common.util.SnowFlakeUtil;
import com.jy.datapipeline.common.util.StringUtil;
import com.jy.datapipeline.importserver.entity.ImportRule;
import com.jy.datapipeline.importserver.entity.ImportSqlldrInfo;
import com.jy.datapipeline.importserver.service.ImportModeService;
import com.jy.datapipeline.importserver.service.ImportSqlldrInfoService;
import com.jy.datapipeline.common.util.TEAUtil;
import com.mysql.cj.util.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * @类名 SqddlrToolModeServiceImpl
 * @描述 TODO
 * @作者 白条君
 * @创建日期 2023/5/31 17:57
 * @版本 1.0
 */
@Service
public class SqddlrImportModeServiceImpl implements ImportModeService {

    private final ImportSqlldrInfoService importSqlldrInfoService;

    private final DataSourceInfoService dataSourceInfoService;

    @Lazy
    public SqddlrImportModeServiceImpl(ImportSqlldrInfoService importSqlldrInfoService,
                                       DataSourceInfoService dataSourceInfoService) {
        this.importSqlldrInfoService = importSqlldrInfoService;
        this.dataSourceInfoService = dataSourceInfoService;
    }

    @Override
    public void executionImportModeService(@NotNull ImportRule importRule) throws GlobalException {
        //查找目标数据源的jdbcurl
        DataSourceInfoModel dataSourceInfoModel = dataSourceInfoService.findByDataSourceId(importRule.getDataSourceId());
        String jdbcUrl = dataSourceInfoModel.getJdbcUrl();

        //通过目标数据源的jdbcurl获取sqlldr信息
        if (StringUtils.isNullOrEmpty(jdbcUrl)) {
            throw new GlobalException(ExpConstants.TARGET_DATASOURCE_EXP);
        }

        ImportSqlldrInfo importSqlldrInfo = importSqlldrInfoService.getImportSqlldrInfo(jdbcUrl);
        importSqlldrInfo.setUsername(dataSourceInfoModel.getUserName());
        importSqlldrInfo.setPassword(TEAUtil.decode(dataSourceInfoModel.getPassword()));
        importSqlldrInfo.setSid(importRule.getSid());
        importSqlldrInfo.setSqlldrParams(importRule.getSqlldrParams());
        String sqlldrId = StringUtil.concat(new StringBuffer(), PrefixConstants.SQLLDR_PREFIX, "_", String.valueOf(SnowFlakeUtil.getNextId()));
        importSqlldrInfo.setSqlldrInfoId(sqlldrId);

        //添加sqllldr信息
        importSqlldrInfoService.addSqlldrInfo(importSqlldrInfo);

        importRule.setSqlldrInfoId(sqlldrId);
    }
}
